import 'package:flutter/material.dart';
import 'product_detail.dart';
import 'package:dio/dio.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:url_launcher/url_launcher.dart';
import '../config/http_headers.dart';
import '../routers/application.dart';
import '../service/service_method.dart';
import '../components/ad_banner.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  int page = 1;
  List<Map> hotGoodsList = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    var formData = {'lon': '115.02932', 'lat': '35.76189'};
    return Scaffold(
        backgroundColor: Color.fromRGBO(244, 245, 245, 1.0),
        appBar: AppBar(title: Text('百姓生活+')),
        body: FutureBuilder(
            future: request('homePageContext', formData: formData),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                var data = json.decode(snapshot.data.toString());
                List<Map> swiperDataList =
                    (data['data']['slides'] as List).cast(); // 轮播图列表
                List<Map> navigatorList =
                    (data['data']['category'] as List).cast(); //类别列表
                if (navigatorList.length > 10) {
                  navigatorList.removeRange(10, navigatorList.length);
                }
                String advertisingPicture =
                    data['data']['advertesPicture']['PICTURE_ADDRESS']; // 广告图
                String leaderImage =
                    data['data']['shopInfo']['leaderImage']; // 店长图片
                String leaderPhone =
                    data['data']['shopInfo']['leaderPhone']; // 店长电话
                List<Map> recommendList =
                    (data['data']['recommend'] as List).cast(); // 推荐商品列表
                String floor1Title =
                    data['data']['floor1Pic']['PICTURE_ADDRESS'];
                String floor2Title =
                    data['data']['floor2Pic']['PICTURE_ADDRESS'];
                String floor3Title =
                    data['data']['floor3Pic']['PICTURE_ADDRESS'];
                List<Map> floor1 =
                    (data['data']['floor1'] as List).cast(); // 楼层商品
                List<Map> floor2 =
                    (data['data']['floor2'] as List).cast(); // 楼层商品
                List<Map> floor3 =
                    (data['data']['floor3'] as List).cast(); // 楼层商品

                return EasyRefresh(
                  child: ListView(
                    children: <Widget>[
                      SwiperDiy(swiperDataList: swiperDataList), // 轮播图组件
                      TopNavigation(navigatorList: navigatorList), //导航组件
                      AdBanner(advertisingPicture: advertisingPicture), // 广告组件
                      LeaderPhone(
                          leaderImage: leaderImage,
                          leaderPhone: leaderPhone), //店长组件
                      Recommend(
                        recommendList: recommendList,
                      ),
                      FloorTitle(
                        pictureAddress: floor1Title,
                      ),
                      FloorContent(
                        floorGoodsList: floor1,
                      ),
                      FloorTitle(
                        pictureAddress: floor2Title,
                      ),
                      FloorContent(
                        floorGoodsList: floor2,
                      ),
                      FloorTitle(
                        pictureAddress: floor3Title,
                      ),
                      FloorContent(
                        floorGoodsList: floor3,
                      ),
                      _hotGoods(),
                    ],
                  ),
                  onLoad: () async {
                    print('开始加载更多');
                    _getHotGoods();
                  },
                  footer: MaterialFooter(),
                );
              } else {
                return Center(child: Text('加载中'));
              }
            }));
  }

  Widget _hotGoods() {
    return Container(
        child: Column(
      children: <Widget>[
        _hotTitle(),
        _wrapList(),
      ],
    ));
  }

  void _getHotGoods() async {
    var res = await request('homePageBelowConten', formData: {'page': page});
    var data = json.decode(res.toString());
    List<Map> newGoodsList = (data['data'] as List).cast();
    setState(() {
      hotGoodsList.addAll(newGoodsList);
      page++;
    });
  }

  Widget _hotTitle() {
    return Container(
        child: Text('火爆专区'),
        margin: EdgeInsets.only(top: 10.0),
        padding: EdgeInsets.all(5.0),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(bottom: BorderSide(width: 0.5, color: Colors.black12))));
  }

  Widget _wrapList() {
    if (hotGoodsList.length > 0) {
      List<Widget> listWidget = hotGoodsList.map((val) {
        return InkWell(
            onTap: () {
              print('点击了火爆商品');
              Application.router
                  .navigateTo(context, "/detail?id=${val['goodsId']}");
            },
            child: Container(
                width: ScreenUtil().setWidth(372),
                color: Colors.white,
                padding: EdgeInsets.all(5.0),
                child: Column(
                  children: <Widget>[
                    Image.network(val['image'],
                        width: ScreenUtil().setWidth(375)),
                    Text(val['name'],
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            color: Colors.pink,
                            fontSize: ScreenUtil().setSp(26))),
                    Row(
                      children: <Widget>[
                        Text('￥${val["mallPrice"]}'),
                        Text('￥${val["price"]}',
                            style: TextStyle(
                                color: Colors.black26,
                                decoration: TextDecoration.lineThrough)),
                      ],
                    )
                  ],
                )));
      }).toList();
      return Wrap(children: listWidget, spacing: 2);
    } else {
      return Center(child: Text('加载中'));
    }
  }
}

class SwiperDiy extends StatelessWidget {
  final List swiperDataList;
  SwiperDiy({Key key, this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
        color: Colors.white,
        height: ScreenUtil().setHeight(333),
        width: ScreenUtil().setWidth(750),
        child: Swiper(
          itemBuilder: (BuildContext context, int index) {
            return InkWell(
                onTap: () {
                  Application.router.navigateTo(context,
                      "/detail?id=${swiperDataList[index]['goodsId']}");
                },
                child: Image.network(
                  "${swiperDataList[index]['image']}",
                  fit: BoxFit.fill,
                ));
          },
          itemCount: swiperDataList.length,
          pagination: SwiperPagination(),
          autoplay: true,
        ));
  }
}

/// 导航菜单组件
class TopNavigation extends StatelessWidget {
  final List navigatorList;
  TopNavigation({Key key, this.navigatorList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(320),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: EdgeInsets.all(4.0),
        children: navigatorList.map((item) {
          return _gridViewItemUI(context, item);
        }).toList(),
      ),
    );
  }

  Widget _gridViewItemUI(BuildContext context, item) {
    return InkWell(
        onTap: () {
          print('点击了导航栏');
        },
        child: Column(
          children: <Widget>[
            Image.network(item['image'],
                width: ScreenUtil().setWidth(95),
                height: ScreenUtil().setHeight(95)),
            Text(item['mallCategoryName'])
          ],
        ));
  }
}

class LeaderPhone extends StatelessWidget {
  final String leaderImage;
  final String leaderPhone;
  LeaderPhone({Key key, this.leaderImage, this.leaderPhone}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: InkWell(
      child: Image.network(this.leaderImage),
      onTap: _launchURL,
    ));
  }

  void _launchURL() async {
    String url = 'tel:' + leaderPhone;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
}

class Recommend extends StatelessWidget {
  final List recommendList;
  Recommend({Key key, this.recommendList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
        height: ScreenUtil().setHeight(380),
        margin: EdgeInsets.only(top: 10.0),
        child: Column(
          children: <Widget>[
            _titleWidget(),
            _recommendList(),
          ],
        ));
  }

  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 0.5, color: Colors.black12))),
      child: Text('商品推荐', style: TextStyle(color: Colors.pink)),
    );
  }

  Widget _item(BuildContext context, int index) {
    return InkWell(
      onTap: () {
        Application.router.navigateTo(
            context, "/detail?id=${recommendList[index]['goodsId']}");
      },
      child: Container(
          height: ScreenUtil().setHeight(330),
          width: ScreenUtil().setWidth(250),
          padding: EdgeInsets.all(18.0),
          decoration: BoxDecoration(
              color: Colors.white,
              border:
                  Border(left: BorderSide(width: 0.5, color: Colors.black12))),
          // todo: 这里有问题，渲染超出界限
          child: Column(
            children: <Widget>[
              Expanded(child: Image.network(recommendList[index]['image'])),
              Text("￥${recommendList[index]['mallPrice']}"),
              Text('￥${recommendList[index]["price"]}',
                  style: TextStyle(
                    color: Colors.grey,
                    decoration: TextDecoration.lineThrough,
                  )),
            ],
          )),
    );
  }

  Widget _recommendList() {
    return Container(
        height: ScreenUtil().setHeight(330),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: recommendList.length,
          itemBuilder: (context, index) {
            return _item(context, index);
          },
        ));
  }
}

class FloorTitle extends StatelessWidget {
  final String pictureAddress;

  FloorTitle({Key key, this.pictureAddress}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8.0),
      child: Image.network(pictureAddress),
    );
  }
}

class FloorContent extends StatelessWidget {
  final List floorGoodsList;
  FloorContent({Key key, this.floorGoodsList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Column(children: <Widget>[
      _firstRow(context),
      _otherGoods(context),
    ]));
  }

  Widget _firstRow(BuildContext context) {
    return Row(
      children: <Widget>[
        _goodsItem(context, floorGoodsList[0]),
        Column(
          children: <Widget>[
            _goodsItem(context, floorGoodsList[1]),
            _goodsItem(context, floorGoodsList[2]),
          ],
        )
      ],
    );
  }

  Widget _otherGoods(BuildContext context) {
    return Row(children: <Widget>[
      _goodsItem(context, floorGoodsList[3]),
      _goodsItem(context, floorGoodsList[4]),
    ]);
  }

  Widget _goodsItem(BuildContext context, Map goods) {
    return Container(
        width: ScreenUtil().setWidth(375),
        child: InkWell(
          child: Image.network(goods['image']),
          onTap: () {
            Application.router
                .navigateTo(context, "/detail?id=${goods['goodsId']}");
          },
        ));
  }
}

/** 下面的是组件demo代码，非项目代码可删掉 */
class HomePageItem extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('水平方向布局'),
        ),
        body: SingleChildScrollView(
            child: Column(
          children: <Widget>[
            ButtonRowGroup(),
            Image.asset('images/prettierrc.png'),
            Text('长按下面图标'),
            Center(
                child:
                    Tooltip(message: '点我点我', child: Icon(Icons.all_inclusive))),
            RequestDemo()
          ],
        )));
  }
}

Future getHttp() async {
  try {
    Response response;
    Dio dio = new Dio();
    dio.options.headers = httpHeaders;
    response =
        await dio.get('https://www.qimao.com/api/report-log/get-report-type/');
    return response.data;
  } catch (e) {
    return print(e);
  }
}

class ButtonRowGroup extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        children: <Widget>[
          new RaisedButton(
              onPressed: () {
                print('red button pressed');
                Navigator.push(
                    context,
                    new MaterialPageRoute(
                        builder: (context) => new SecondScreen()));
              },
              color: Colors.redAccent,
              child: new Text('红色按钮')),
          Expanded(
              child: new RaisedButton(
            onPressed: () {
              print('跳转详情');
              Navigator.push(
                  context,
                  new MaterialPageRoute(
                      builder: (context) => new ProductList(
                          products: List.generate(
                              20, (i) => Product('商品 $i', '这是商品详情，编号$i')))));
            },
            color: Colors.orangeAccent,
            child: new Text('黄色按钮-查看详情'),
          )),
          new RaisedButton(
              onPressed: () {
                _navigateToHH(context);
              },
              color: Colors.pinkAccent,
              child: new Text('粉色按钮')),
        ],
      ),
    );
  }

  _navigateToHH(BuildContext context) async {
    final result = await Navigator.push(
        context, MaterialPageRoute(builder: (context) => HH()));
    Scaffold.of(context).showSnackBar(SnackBar(content: Text('$result')));
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Scaffold(
            appBar: AppBar(title: Text('黄色按钮-详情页面')),
            body: Center(
                child: RaisedButton(
                    child: Text('goBack'),
                    onPressed: () {
                      Navigator.pop(context);
                    }))));
  }
}

/// HH漫画页面Demo
class HH extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Scaffold(
            appBar: AppBar(title: Text('HH漫画')),
            body: Center(
                child: Column(
              children: <Widget>[
                RaisedButton(
                    child: Text('热血风漫画'),
                    onPressed: () {
                      Navigator.pop(context, '热血风漫画');
                    }),
                RaisedButton(
                    child: Text('校园风漫画'),
                    onPressed: () {
                      Navigator.pop(context, '校园风漫画');
                    }),
              ],
            ))));
  }
}

/// Dio插件请求Demo
class RequestDemo extends StatefulWidget {
  @override
  _RequestDemoState createState() => _RequestDemoState();
}

class _RequestDemoState extends State<RequestDemo> {
  String showText = '还没请求数据';
  @override
  Widget build(BuildContext context) {
    return Container(
        child: SingleChildScrollView(
      child: Column(
        children: <Widget>[
          RaisedButton(
            child: Text('请求数据'),
            onPressed: () {
              _postGeek();
            },
          ),
          Text(showText),
        ],
      ),
    ));
  }

  void _postGeek() {
    getHttp().then((resp) {
      print(resp);
      setState(() {
        showText = resp;
      });
    });
  }
}
